package com.example.demo.util;

import com.example.demo.pojo.vo.TetsVO;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vaintale
 * @date 2025/6/26
 */
public class CsvAverageCalculator {
    public static void main(String[] args) {
        String csvFile = "/home/vaintale/projecs/java-code/demo/src/main/resources/data/graph/graph_Fdelay.csv";
        ArrayList<TetsVO> tetsVOS = new ArrayList<>();
        Integer key = 0;
        try (Reader reader = new FileReader(csvFile);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {

            for (CSVRecord record : csvParser) {
                List<Double> rowValues = new ArrayList<>();

                // 遍历当前行的所有列
                for (int i = 0; i < record.size(); i++) {
                    String value = record.get(i);
                    try {
                        double numericValue = Double.parseDouble(value);
                        rowValues.add(numericValue);
                    } catch (NumberFormatException e) {
                        System.err.println("非数值数据: " + value);
                    }
                }


                // 计算当前行的平均值
                if (!rowValues.isEmpty()) {
                    TetsVO tetsVO = new TetsVO();
                    double sum = 0;
                    for (double value : rowValues) {
                        sum += value;
                    }
                    double average = sum / rowValues.size();
                    key = key + 1;
                    tetsVO.setTime(key);
                    tetsVO.setValue(String.valueOf(average));
                    tetsVOS.add(tetsVO);
                  //  System.out.println("当前行平均值: " + average);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        tetsVOS.forEach(System.out::println);
    }
}
